package com.android.tea.util;


import java.util.ArrayList;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Rect;
import android.media.AudioManager;
import android.os.Build;
import android.os.Environment;
import android.os.SystemClock;
import android.view.Window;
import android.view.WindowManager;

import com.android.tea.AlarmReceiver;
import com.android.tea.BaseTabActivity;
import com.android.tea.MainActivity;
import com.android.tea.R;
import com.android.tea.TeaMessageActivity;
import com.android.tea.config.Config;
import com.android.tea.data.SettingLoader;
import com.android.tea.entity.Order;
import com.android.tea.entity.Recommend;
import com.android.tea.entity.VersionInfo;

public class Utils {

	private static final String TAG = "Utils";

	public static final int byteToShort(byte[] bytes) {
		return (bytes[0] << 8) + (bytes[1] & 0xFF);
	}

	public static boolean isSDCardEnable() {
		String SDState = Environment.getExternalStorageState();
		if (SDState != null && SDState.equals(android.os.Environment.MEDIA_MOUNTED)) {
			return true;
		}
		return false;
	}

	/**
	 * 将dip转换为pix
	 * 
	 * @param context
	 * @param dip
	 * @return
	 */
	public static int dipToPixels(Context context, float dip) {
		return (int) (context.getResources().getDisplayMetrics().density * dip);
	}


	public static VersionInfo.UpdateType getAppVersionUpdateType(Context context, String newVersion) {
		VersionInfo.UpdateType type = VersionInfo.UpdateType.NO_UPDATE;
		String localVersion = getLocalAppVersion(context);
		try {
			int[] localVersionArray = getVersionNum(localVersion);
			int[] newVersionArray = getVersionNum(newVersion);
			if (newVersionArray[0] > localVersionArray[0]) {
				return VersionInfo.UpdateType.UPDATE_AND_PROMPT;
			} else if (newVersionArray[0] == localVersionArray[0]) {
				if (newVersionArray[1] > localVersionArray[1]) {
					return VersionInfo.UpdateType.UPDATE_AND_PROMPT;
				} else if (newVersionArray[1] == localVersionArray[1]) {
					if (newVersionArray[2] > localVersionArray[2]) {
						return VersionInfo.UpdateType.UPDATE_AND_PROMPT;
					} else if (newVersionArray[2] == localVersionArray[2]) {
						if (newVersionArray[3] > localVersionArray[3]) {
							return VersionInfo.UpdateType.UPDATE_NO_PROMPT;
						}
					}
				}
			}
		} catch (Exception e) {
			TeaLog.e(TAG, e);
		}
		return type;
	};

	public static int[] getVersionNum(String version) {
		int[] versionIntArray = new int[4];
		String[] versionStringArray = version.split("[.]");
		int versionStringLenth = versionStringArray.length;
		for (int i = 0; i < 4; i++) {
			if (i < versionStringLenth) {
				try {
					versionIntArray[i] = Integer.parseInt(versionStringArray[i]);
				} catch (Exception e) {
					TeaLog.e(TAG, e);
					versionIntArray[i] = 0;
				}
			} else {
				versionIntArray[i] = 0;
			}
		}
		return versionIntArray;
	}

	/**
	 * 获取本地app版本号
	 * 
	 * @param context
	 * @return
	 */
	public static String getLocalAppVersion(Context context) {
		PackageManager pm = context.getPackageManager();
		String version = null;
		try {
			version = pm.getPackageInfo("com.gozap.chouti", 0).versionName;
		} catch (NameNotFoundException e) {
			TeaLog.e(TAG, e);
		}
		return version;
	}

	/**
	 * 获取屏幕宽度(像素)
	 * 
	 * @param context
	 * @return
	 */
	public static int getScreenWidth(Context context) {
		WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		return windowManager.getDefaultDisplay().getWidth();
	}

	/**
	 * 获取状态栏高度
	 * 
	 * @param window
	 * @return
	 */
	public static int getStatusBarHeight(Window window) {
		Rect outRect = new Rect();
		window.getDecorView().getWindowVisibleDisplayFrame(outRect);
		return outRect.top;
	}

	/**
	 * 获取屏幕高度(像素)
	 * 
	 * @param context
	 * @return
	 */
	public static int getScreenHeight(Context context) {
		WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		return windowManager.getDefaultDisplay().getHeight();
	}

	/**
	 * 根据不同设备的分辨率获取适合的图片尺寸
	 * 
	 * @param url
	 * @return
	 */
	public static String getFitScreenImageUrl(String url, int size) {
		String returnUrl = "";

		int i = url.lastIndexOf(".");
		int length = url.length();
		String urlName = "";
		String suffix = "";
		if (i < length && i > 0) {
			urlName = url.substring(0, i);
			suffix = url.substring(i, length);
		} else {
			urlName = url;
		}
		int imageW = size;
		/**
		 * 锁定比例,按照固定尺寸取小值缩小(只允许缩小) 协议类型 < width >x< height>) 例如：600x200)
		 * 首先该协议转换后的图片不能是放大的，缩小的时候按照比例，取小值进行缩小
		 */
		returnUrl = urlName + "=C" + imageW + "x" + imageW + suffix + "?quality=70";
		return returnUrl;
	}

	/**
	 * 获取设备版本
	 */
	public static String getPlatform() {
		String releaseversion = Build.VERSION.RELEASE;
		String version = "AR";
		if (releaseversion.contains("1.5")) {
			version = "AR_15";
		} else if (releaseversion.contains("1.6")) {
			version = "AR_16";
		} else if (releaseversion.contains("2.0")) {
			version = "AR_20";
		} else if (releaseversion.contains("2.1")) {
			version = "AR_21";
		} else if (releaseversion.contains("2.2")) {
			version = "AR_22";
		} else if (releaseversion.contains("2.3")) {
			version = "AR_23";
		} else if (releaseversion.contains("3.0")) {
			version = "AR_30";
		} else if (releaseversion.contains("3.1")) {
			version = "AR_31";
		} else if (releaseversion.contains("3.2")) {
			version = "AR_32";
		} else if (releaseversion.contains("4.0")) {
			version = "AR_40";
		}
		return version;
	}

	public static void showNotification(Context context, int id,Recommend recommend) {
		NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);

        String tickerText = recommend.getContent();

        Notification notification = new Notification(R.drawable.tea_logo, tickerText, System.currentTimeMillis());
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        notification.defaults |= Notification.DEFAULT_SOUND;
        Intent intent = null;
        if ("gonggao".equals(recommend.getType())) {
			intent = new Intent(context, MainActivity.class);
		}else {
			intent = new Intent(context,TeaMessageActivity.class);
			intent.putExtra("url", recommend.getUrl());
			intent.putExtra("from", true);
		}
      
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("from_notification", true);
        
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        
        notification.setLatestEventInfo(context, recommend.getContent(), tickerText, contentIntent);
        
//        notification.flags |= Notification.FLAG_ONGOING_EVENT;
//        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        notificationManager.notify(id, notification);
	}
	
	public static void showNotification(Context context, int id, String title, String message, int type)
	{
		NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);

        String tickerText = message;

        Notification notification = new Notification(R.drawable.tea_logo, tickerText, System.currentTimeMillis());
        notification.defaults |= Notification.DEFAULT_SOUND;
        Intent intent = new Intent(context, TeaMessageActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("from_notification", true);
        
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        
        notification.setLatestEventInfo(context, title, tickerText, contentIntent);
        
//        notification.flags |= Notification.FLAG_ONGOING_EVENT;
//        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        notificationManager.notify(id, notification);
	}
	

	
	public static void showNotification(Context context, ArrayList<Recommend> list,
			boolean autoClear) {
		if(list!=null&&list.size()>0) {
			NotificationManager notificationManager = (NotificationManager) context
					.getSystemService(Context.NOTIFICATION_SERVICE);

			String tickerText = context.getResources().getString(
					R.string.push_tips_title);
			String tickerContent = String.format(context.getResources().getString(
					R.string.push_tips_content),list.size());
			Notification notification = new Notification(R.drawable.tea_logo,
					tickerText, System.currentTimeMillis());
			if (autoClear) {
				notification.flags = Notification.FLAG_AUTO_CANCEL;
			} else {
				notification.flags = Notification.FLAG_ONGOING_EVENT;
			}
			Intent intent = new Intent(context, BaseTabActivity.class);
			intent.putExtra("fromNotify", true);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
					| Intent.FLAG_ACTIVITY_CLEAR_TOP);
			PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
					intent, PendingIntent.FLAG_UPDATE_CURRENT);

			notification.defaults = Notification.DEFAULT_ALL;
			notification.audioStreamType = AudioManager.ADJUST_LOWER;
			notification.contentIntent = contentIntent;

			notification.setLatestEventInfo(context, tickerText, tickerContent,
					contentIntent);
			int id = (int) System.currentTimeMillis();
			notificationManager.notify(id, notification);
		}
		
	}
	
	public static void deleteNotification(Context context, int id) 
	{
        NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancel(id);
    }

	public static void registerAlarm(Context context) {
		Intent intent = new Intent(context,AlarmReceiver.class);  
        PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0); 
		AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);   
		am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), Config.IntervalTime, pi);  
	}
	
	public static void unRegisterAlarm(Context context) {
		 Intent intent = new Intent(context,AlarmReceiver.class);  
         PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);  
         AlarmManager am = (AlarmManager) context.getSystemService(Activity.ALARM_SERVICE);  
         am.cancel(pi);  
	}

	
}
